﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using Communergy.PachubeLibrary;
using Communergy.NationalGridDataServices;
using Communergy.Data;

public partial class RealtimeCarbonIntensity : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var eeml = new eeml();
        
        var eemlEnv = new eemlEnvironment();
        eemlEnv.title = "National Grid Realtime Carbon Intensity";
        eemlEnv.updated = DateTime.Now;
        eemlEnv.updatedSpecified = true;
        eemlEnv.website = "http://realtimecarbon.org/";

        //eemlEnvironmentLocation location = new eemlEnvironmentLocation();
        //location.Name = "Slough";
        //location.exposure = eemlEnvironmentLocationExposure.indoor;
        //location.domain = eemlEnvironmentLocationDomain.physical;
        //location.lat = 51.514526;
        //location.lon = -0.594696;

        //eemlEnv.location = location;


                string url = "http://www.realtimecarbon.org/ws/electricity/services/co2profile/5minute/item";

                var currentCarbonIntensityXml = GridDataHelper.GetRemoteXml(url);
                var liveCarbonIntensityData = GridDataHelper.LiveCarbonIntensityFromXml(currentCarbonIntensityXml);
                var liveCarbonIntensity = NationalGridDataHelper.CreateLiveCarbonIntensity(liveCarbonIntensityData);
                if (liveCarbonIntensity != null)
                {


                    eemlEnvironmentData liveCo2 = new eemlEnvironmentData();
                    liveCo2.id = "co2";
                    liveCo2.tag = new string[] { "live Co2", };
                    liveCo2.value = new eemlEnvironmentDataValue { Value = liveCarbonIntensity.lc_carbonIntensity.Value.ToString("0.000") };
                    liveCo2.unit = new eemlEnvironmentDataUnit { symbol = "kg p/kWh", type = eemlEnvironmentDataUnitType.derivedUnits };
                    
                    
                    eemlEnvironmentData averageCo2 = new eemlEnvironmentData();
                    averageCo2.id = "averageCo2";
                    averageCo2.tag = new string[] { "Average Co2" };
                    averageCo2.value = new eemlEnvironmentDataValue { Value = liveCarbonIntensity.lc_rollingMeanCarbonIntensity.Value.ToString("0.000") };
                    averageCo2.unit = new eemlEnvironmentDataUnit { symbol = "kg p/kWh", type = eemlEnvironmentDataUnitType.derivedUnits };


                    var data = new eemlEnvironmentData[] { liveCo2, averageCo2 };
                    eemlEnv.data = data;



                    eeml.Items = new eemlEnvironment[] { eemlEnv };
                    var output = SerializeObjectToBytes(eeml);
                    var asString = UTF8ByteArrayToString(output);

                    // Send the XML file to the web browser for download.
                    Response.Clear();
                    //Response.AppendHeader("Content-Disposition","filename=BasicWeather.xml" );
                    //Response.AppendHeader("Content-Length", ms.Length.ToString());
                    Response.ContentType = "text/xml";
                    Response.Write(asString);
                }
        
    }

    public static byte[] SerializeObjectToBytes(object SerializeObject)
    {
        try
        {
            MemoryStream memoryStream = new MemoryStream();

            XmlSerializer xs = new XmlSerializer(SerializeObject.GetType());
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            xs.Serialize(xmlTextWriter, SerializeObject);
            return memoryStream.ToArray();
        }
        catch (Exception ex)
        {
            throw new Exception("Failed to serialize object.", ex);
        }
    }

    /// <summary>
    /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
    /// </summary>
    /// <param Name="characters">Unicode Byte Array to be converted to String</param>
    /// <returns>String converted from Unicode Byte Array</returns>
    private String UTF8ByteArrayToString(Byte[] characters)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        String constructedString = encoding.GetString(characters);
        return (constructedString);
    }
}


[Serializable]
public class TestSer
{
    public string Name { get; set; }
}
